package encrypt.demo;

import java.security.Key;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class AESUtils {

    // AES算法名称
    private static final String ALGORITHM = "AES";

    // AES加密模式和填充方式
    public static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    // 密码长度，必须为16位
    private static final int KEY_LENGTH = 16;

    public static String keyToString(Key key) {
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }

    public static Key stringToKey(String keyString) {
        byte[] decodedKey = Base64.getDecoder().decode(keyString);
        return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
    }


    // 根据密码生成密钥对象
    public static Key generateKey(String password) {
        // 如果密码长度不足16位，用0补齐
        int j = KEY_LENGTH - password.length();
        if (password.length() < KEY_LENGTH) {
            for (int i = 0; i < j ; i++) {
                password = password + "0";
            }
        }
        // 如果密码长度超过16位，截取前16位
        if (password.length() > KEY_LENGTH) {
            password = password.substring(0, KEY_LENGTH);
        }
        // 将密码转换为字节数组
        byte[] keyBytes = password.getBytes();
        // 生成密钥对象
        Key key = new SecretKeySpec(keyBytes, ALGORITHM);
        return key;
    }

}
